//引入数据库连接模块
const db = require('../../db/connMysql');
const OpenAI = require("openai");
const openai = new OpenAI({
    baseURL: 'https://api.deepseek.com',
    apiKey: 'sk-f6884c0f138248a19e8a9869da52952c',
    dangerouslyAllowBrowser: true 
});

const chatDao = {
    /*
     * 获取某个学生测评记录限制在院系内
     */
    async getAllChatHistory() {
        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    connection.release();
                    reject(err);
                    return ;
                }
                let sql = `select * from chatHistory`;
                connection.query(sql,function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
            });
        });
        return result;
    },
    async addChatHistory(message,is_robot){
        // is_robot = Boolean(is_robot);
        console.log("【is_robot的值】",is_robot)
        if(is_robot === 'true'){
            is_robot = 1;
        }
        else{
            is_robot = 0;
        }
        
        // 新增参数校验
        // if (typeof message !== 'string' || message.trim() === '') {
        //     throw new Error('message参数必须为非空字符串');
        // }
        // if (typeof is_robot !== 'number' && typeof is_robot !== 'boolean') {
        //     console.log(typeof is_robot);
        //     throw new Error('is_robot参数必须为布尔值或数字');
        // }

        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    connection.release();
                    reject(err);
                    return ;
                }
                // 修改SQL语句，添加单引号并使用预处理
                let sql = `INSERT chatHistory (message,is_robot) VALUES (?, ?)`;
                connection.query(sql, [message, is_robot], function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
                
            });
        });
        return result;
    },

    /**
     * @description deepSeek流式数据返回接口
     */
    async getChatStreamRequest(req, res) {

        const { message } = req.body;
        console.log("【接收到前端发来的数据+++】",message);
        
        try {
            // 设置流式响应头
            res.writeHead(200, {
                'Content-Type': 'text/event-stream',
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive',
                'Access-Control-Allow-Origin': '*'
            });

            // 创建流式响应
            const completion = await openai.chat.completions.create({
                messages: [{ 
                    role: "system", 
                    content: message 
                }],
                model: "deepseek-chat",
                stream: true
            });

            // 逐块发送数据
            for await (const chunk of completion) {
                const content = chunk.choices[0]?.delta?.content || '';
                console.log('【流式数据】',content);
                res.write(`${content}`); // SSE格式
            }
            
        } catch (err) {
            console.error('【请求出错】', err);
            res.write(`event: error\ndata: ${JSON.stringify({ error: true })}\n\n`);
        } finally {
            res.end(); // 确保连接关闭
        }
    },
    async getShopCar(){
        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    connection.release();
                    reject(err);
                    return ;
                }
                let sql = `select * from shopcar`;
                connection.query(sql,function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
            });
        });
        return result;

    },
    async addNumShopCar(){
        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    connection.release();
                    reject(err);
                    return ;
                }
                // let sql = `select * from shopcar`;
                let sql = `UPDATE shopcar
                            SET number = number + 1
                            WHERE commodity_id = 1;`;
                connection.query(sql,function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
            });
        });
        return result;

    },
};

module.exports = chatDao;